package com.chen.config;

import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
import com.chen.realm.MyRealm;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;

@Configuration
public class ShiroConfig {


    //shiroFactoryBean,注册bean，所有的配置都在此类中进行。
    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("securityManager") DefaultWebSecurityManager defaultWebSecurityManager ){

        ShiroFilterFactoryBean factoryBean = new ShiroFilterFactoryBean();

        HashMap<String, String> map = new HashMap<>();

        //设置登陆后才能访问
        map.put("/admin/*","authc");
        map.put("/error/*","authc");
        map.put("/common/*","authc");

        //分配权限
        map.put("/emp/all","perms[admin:all]");
        map.put("/emp/toAdd","perms[admin:all]");
        map.put("/emp/toUpdate","perms[admin:all]");

        //设置拦截路径
        factoryBean.setFilterChainDefinitionMap(map);

        //设置登录页面
        factoryBean.setLoginUrl("/index");

        //未授权页面
        factoryBean.setUnauthorizedUrl("/unauth");

        //设置securityManager管理
        factoryBean.setSecurityManager(defaultWebSecurityManager);

        return factoryBean;

    }

    //DefaultWebSecurityManager 注册bean
    @Bean(name = "securityManager")
    public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("getMyRealm") MyRealm realm){

        //把注册好的realm给securityManager
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        securityManager.setRealm(realm);
        //返回它
        return securityManager;
    }


    //realm注册bean
    @Bean
    public MyRealm getMyRealm(){
        return new MyRealm();
    }



    //整合thymeleaf的方言
    @Bean
    public ShiroDialect shiroDialect() {
        return new ShiroDialect();
    }

}
